package pers.qianyu.service.impl;

import lombok.extern.slf4j.*;
import org.springframework.stereotype.*;
import pers.qianyu.exception.*;
import pers.qianyu.service.*;

import java.io.*;

/**
 * 本地文件上传服务实现类
 *
 * @author mizzle rain
 * @date 2020-10-14 11:27
 */
@Slf4j
@Service(value = "localFileServiceImpl")
public class LocalFileServiceImpl implements FileService {
    /**
     * 存储空间
     */
    private static final String BUCKET = "uploads";

    @Override
    public void upload(InputStream in, String fileName) {
        String storagePath = BUCKET + "/" + fileName;
        try (InputStream inputStream = in;
             FileOutputStream out = new FileOutputStream(storagePath)) {
            byte[] buffer = new byte[1024];
            int len;
            while ((len = inputStream.read(buffer)) > 0) {
                out.write(buffer, 0, len);
            }
            out.flush();
        } catch (Exception e) {
            log.error("文件上传失败：{}", e.getMessage());
            throw new BusinessException(ErrorCodeEnum.FILE_UPLOAD_FAILURE, e);
        }
    }

    @Override
    public void upload(File file) {
        try {
            upload(new FileInputStream(file), file.getName());
        } catch (FileNotFoundException e) {
            log.error("文件上传失败：{}", e.getMessage());
            throw new BusinessException(ErrorCodeEnum.FILE_UPLOAD_FAILURE, e);
        }
    }
}
